package com.springsecurity.demo.service.impl;


import com.springsecurity.demo.config.JWTLogoutCache;
import com.springsecurity.demo.controller.HelloController;
import com.springsecurity.demo.model.dto.AuthLoginRequest;
import com.springsecurity.demo.model.entity.LoginUser;
import com.springsecurity.demo.model.entity.Users;
import com.springsecurity.demo.service.LoginServcie;
import com.springsecurity.demo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LoginServiceImpl implements LoginServcie {

    private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JWTLogoutCache jwtLogoutCache;

    @Value("${jwt.tokenTTL}")
    private String jwtTTL;

//    @Autowired
//    private RedisCache redisCache;

//    @Override
//    public ResponseResult login(User user) {
//        //AuthenticationManager authenticate进行用户认证
//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
//        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        //如果认证没通过，给出对应的提示
//        if(Objects.isNull(authenticate)){
//            throw new RuntimeException("登录失败");
//        }
//        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
//        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
//        String userid = loginUser.getUser().getId().toString();
//        String jwt = JwtUtil.createJWT(userid);
//        Map<String,String> map = new HashMap<>();
//        map.put("token",jwt);
//        //把完整的用户信息存入redis  userid作为key
//        redisCache.setCacheObject("login:"+userid,loginUser);
//        return new ResponseResult(200,"登录成功",map);
//    }
//
//    @Override
//    public ResponseResult logout() {
//        //获取SecurityContextHolder中的用户id
//        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        Long userid = loginUser.getUser().getId();
//        //删除redis中的值
//        redisCache.deleteObject("login:"+userid);
//        return new ResponseResult(200,"注销成功");
//    }

    @Override
    public Map<String,String> login(AuthLoginRequest authLoginRequest) {

        //AuthenticationManager authenticate进行用户认证
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    authLoginRequest.getUsername(),
                    authLoginRequest.getPassword());
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            //如果认证没通过，给出对应的提示
            if(Objects.isNull(authenticate)){
                throw new RuntimeException("登录失败");
            }
            //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) authenticate.getAuthorities();
            JSONArray authoritiesJsonArray = new JSONArray();
            for (GrantedAuthority authority : authorities) {
                authoritiesJsonArray.put(authority.getAuthority().toString());
            }
//            Users user = loginUser.getUser();
//            String userid = user.getId().toString();

            Map<String, Object> subjectMap = new HashMap<>();
            subjectMap.put("username", loginUser.getUsername());
            subjectMap.put("password", loginUser.getPassword());
            subjectMap.put("authorities", authoritiesJsonArray);
            JSONObject jsonObject = new JSONObject(subjectMap);

//        String userid = loginUser.getUser().getId().toString();
            String jwt = JwtUtil.createJWT(JwtUtil.getUUID(), jsonObject.toString(), Long.parseLong(jwtTTL));
            Map<String,String> map = new HashMap<>();
            map.put("token",jwt);
            //把完整的用户信息存入redis  userid作为key
//        redisCache.setCacheObject("login:"+userid,loginUser);
//        return new ResponseResult(200,"登录成功",map);
            return map;
        } catch (RuntimeException e) {
            log.error("error {}", e);
            return null;
        }
    }

    @Override
    public boolean logout(String token) {
        //获取SecurityContextHolder中的用户id
        try {
            jwtLogoutCache.put(token, Long.parseLong(jwtTTL));
        } catch (Exception e) {
            log.error("error {}", e);
            return false;
        }
        return true;
    }
}

